package com.xgpro.pc.rolemanage.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xgpro.common.dingtalk.auth.AuthHelper;
import com.xgpro.common.dingtalk.service.contact.DDUserService;
import com.xgpro.common.results.PageResult;
import com.xgpro.domain.archives.entity.*;
import com.xgpro.domain.rolemanage.dto.UserDTO;
import com.xgpro.domain.rolemanage.entity.Department;
import com.xgpro.domain.rolemanage.entity.Role;
import com.xgpro.domain.studycentre.entity.DaiTuTea;
import com.xgpro.domain.studycentre.entity.Edu;
import com.xgpro.domain.studycentre.entity.TeacherStudent;
import com.xgpro.domain.talentintroduction.dto.UserMessage;
import com.xgpro.domain.talentintroduction.entity.User;
import com.xgpro.domain.talentintroduction.vo.UserInfo;
import com.xgpro.mapper.archives.*;
import com.xgpro.mapper.message.MessageMapper;
import com.xgpro.mapper.rolemanage.DepartmentMapper;
import com.xgpro.mapper.studycentre.DaiTuTeaMapper;
import com.xgpro.mapper.studycentre.EduMapper;
import com.xgpro.mapper.studycentre.TeacherAndStudentMapper;
import com.xgpro.pc.rolemanage.service.DepartmentService;
import com.xgpro.pc.rolemanage.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import com.xgpro.mapper.talentintroduction.UserMapper;
import javax.annotation.Resource;
import java.util.*;

/**
 * @program: xg_dev
 * @description: 用户管理实现类
 * @author: likai
 * @create: 2019-10-07 19:47
 **/

@Service
@Transactional(readOnly = false)
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private DDUserService ddUserService;

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private EduMapper eduMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private DaiTuTeaMapper daiTuTeaMapper;

    @Resource
    private TeacherAndStudentMapper teacherAndStudentMapper;

    @Resource
    private SixSigmaMapper sixSigmaMapper;

    @Resource
    private ExcelImportMapper excelImportMapper;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private PatentMapper patentMapper;

    @Resource
    private PerForManceMapper perForManceMapper;

    @Resource
    private RankApprovalMapper rankApprovalMapper;

    @Value("${DD_ENV.APP_KEY}")
    private String APP_KEY;

    @Value("${DD_ENV.APP_SECRET}")
    private String APP_SECRET;

    /**
     * 根据id获取用户详细信息
     * @param userId
     * @return
     */
    @Override
    public User getUserInfoByUserId(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        List<Role> roleList = userMapper.findRoleListById(userId);
        Set<Role> set = new HashSet<>(roleList);
        user.setRoles(set);
        return user;
    }

    /**
     * 更新用户信息
     * @param user
     * @throws Exception
     */
    @Override
    public void updateUser(User user) throws Exception {
        if (user.getUsername().contains("(已离职)")){
            user.setUsername(user.getUsername().replace("(已离职)",""));
        }
        userMapper.updateByPrimaryKeySelective(user);

    }

    /**
     * 根据条件分页查询用户列表
     * @param pageNum
     * @param pageSize
     * @param param
     * @return
     */
    @Override
    public PageResult<UserDTO> listUser(int pageNum, int pageSize, Map<String, Object> param) {

        PageHelper.startPage(pageNum,pageSize);
        Page<UserDTO> users =(Page<UserDTO>) userMapper.findListBycondition(param);
        PageResult<UserDTO> pageResult = new PageResult(users.getTotal(),users.getResult(),pageNum);


        return  pageResult;

/*
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIsNotNull("deptId");

        String name = (String) param.get("name");
        Object dept = param.get("dept");
        Object education = param.get("education");
        String userId = (String) param.get("userId");
        if (!StringUtils.isEmpty(name)){
            criteria.andLike("username","%"+name+"%");
        }
        if(!ObjectUtils.isEmpty(dept)){
            criteria.andEqualTo("deptId",dept);
        }
        if(!ObjectUtils.isEmpty(education)){
            criteria.andEqualTo("eduId",education);
        }
        if (!StringUtils.isEmpty(userId)){
            criteria.andEqualTo("userId",userId);
        }

        PageHelper.startPage(pageNum,pageSize);
        Page<User> users =(Page<User>) userMapper.selectByExample(example);


        List<UserDTO> list  = new ArrayList<>();
        if (!CollectionUtils.isEmpty(users.getResult())){
            for (User row : users.getResult()) {

                UserDTO userDTO = new UserDTO();
                BeanUtils.copyProperties(row,userDTO);
                if (!ObjectUtils.isEmpty(userDTO.getDeptId())){
                    Example example1 = new Example(Department.class);
                    Example.Criteria criteria1 = example1.createCriteria();
                    criteria1.andEqualTo("ddId",userDTO.getDeptId());
                    List<Department> departments = departmentMapper.selectByExample(example1);
                    userDTO.setDeptName(departments.get(0).getName());
                }
                if (!ObjectUtils.isEmpty(userDTO.getEduId())){
            }
        }
*/


    }

    /**
     * 根据id删除用户
     * @param userId
     */
    @Override
    public void deleteUserInfo(Integer userId) {

        //查询出用户
        User user = userMapper.selectByPrimaryKey(userId);
        if (!ObjectUtils.isEmpty(user)){

            //删除导师带徒
            Example example = new Example(DaiTuTea.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId",user.getId());
            daiTuTeaMapper.deleteByExample(example);

            //更新用户姓名为已离职

            user.setUsername(user.getUsername()+"(已离职)");
            userMapper.updateByPrimaryKeySelective(user);

            /*//删除用户
            userMapper.deleteByPrimaryKey(userId);
            //删除用户所拥有的角色
            userMapper.deleteUserRoleByUserId(userId);
            //删除用户的消息
            messageMapper.deleteMsgByUserId(userId);
            //删除用户学历
            if (!ObjectUtils.isEmpty(user.getEduId())){
                eduMapper.deleteByPrimaryKey(user.getEduId());
            }

            Example example = new Example(SixSigma.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId",userId);
            sixSigmaMapper.deleteByExample(example);

            Example projectExample = new Example(Project.class);
            Example.Criteria projectCriteria = projectExample.createCriteria();
            projectCriteria.andEqualTo("userId",userId);
            projectMapper.deleteByExample(projectExample);

            excelImportMapper.deleteTitle(userId);

            Example patentExample = new Example(Patent.class);
            Example.Criteria patentCriteria = patentExample.createCriteria();
            patentCriteria.andEqualTo("userId",userId);
            patentMapper.deleteByExample(patentExample);

            Example performanceExample = new Example(PerForMance.class);
            Example.Criteria performanceExampleCriteria = performanceExample.createCriteria();
            performanceExampleCriteria.andEqualTo("userId",userId);
            perForManceMapper.deleteByExample(performanceExample);

            Example rankApprovalExample = new Example(RankApproval.class);
            Example.Criteria rankApprovalExampleCriteria = rankApprovalExample.createCriteria();
            rankApprovalExampleCriteria.andEqualTo("userId",userId);
            rankApprovalMapper.deleteByExample(rankApprovalExample);*/
        }


    }

    /**
     * 增加一个用户
     * @param user
     */
    @Override
    public void addUser(User user) {
        //新增时，给用户默认角色


        userMapper.insert(user);
        userMapper.assignRole(user.getId(),3);

    }

    @Override
    public Set<Role> findRoleListByUserId(Integer userId) {
        List<Role> roleListById = userMapper.findRoleListById(userId);
        Set<Role> set = new HashSet<>(roleListById);

        return set;
    }

    @Override
    public void importDDUser(String code) throws Exception {

        //获取toden
        String accessToken = AuthHelper.getAccessToken(APP_KEY, APP_SECRET);

        //同步钉钉部门数据
        List<Department> departmentList = ddUserService.getAllDepertmentId(accessToken);
        for (Object o : departmentList) {
            Department department = (Department)o;

            departmentService.addDept(department);
        }

    }

    @Override
    public void assignRole(Map<String, Object> param) {

        Integer userId = (int)param.get("userId");
        userMapper.deleteUserRoleByUserId(userId);


        List<Integer> roleIds = (List<Integer>) param.get("roleIds");

        if (!CollectionUtils.isEmpty(roleIds)){

            for (Integer roleId : roleIds) {
                userMapper.assignRole(userId,roleId);
            }

        }

    }

    @Override
    public void updateUserDetail(Map<String, Object> param) {
        String job = (String) param.get("job");
        Object educationId = param.get("educationId");
        Integer education= (int)param.get("education");
        String school = (String) param.get("school");
        String garTime = (String) param.get("graTime");
        String major = (String) param.get("major");
        Integer userId = (int)param.get("userId");
        if (ObjectUtils.isEmpty(educationId)){
            //新增用户详情
            Edu edu = new Edu();
            edu.setEduKind(education);
            edu.setSchool(school);
            edu.setGraTime(garTime);
            edu.setMajor(major);
            eduMapper.insert(edu);
            Integer id = edu.getId();
            User user = new User();
            user.setId(userId);
            user.setJob(job);
            user.setEduId(id);
            userMapper.updateByPrimaryKeySelective(user);

        }else {
            //更新用户详情
            Edu edu = new Edu();
            edu.setId((int)educationId);
            edu.setEduKind(education);
            edu.setSchool(school);
            edu.setGraTime(garTime);
            edu.setMajor(major);
            eduMapper.updateByPrimaryKeySelective(edu);
            User user = new User();
            user.setId(userId);
            user.setJob(job);
            userMapper.updateByPrimaryKeySelective(user);

        }
    }

    @Override
    public void updateTeaRalation(Map<String, Object> param) {
        if ((boolean)param.get("flag")){
            //开启导师身份
            Integer userId = (int)param.get("userId");

            DaiTuTea daiTuTea = new DaiTuTea();
            daiTuTea.setUserId(userId);
            daiTuTea.setIntroduce((String)param.get( "introduce"));
            Example example = new Example(DaiTuTea.class);
            Example.Criteria exampleCriteria = example.createCriteria();
            exampleCriteria.andEqualTo("userId",userId);
            List<DaiTuTea> daiTuTeas = daiTuTeaMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(daiTuTeas)){
                daiTuTeaMapper.updateByExampleSelective(daiTuTea,example);
            }else {

                daiTuTeaMapper.insertSelective(daiTuTea);
            }

        }else {
            //关闭导师身份
            Integer userId = (int)param.get("userId");

            Example example = new Example(DaiTuTea.class);
            Example.Criteria exampleCriteria = example.createCriteria();
            exampleCriteria.andEqualTo("userId",userId);
            List<DaiTuTea> daiTuTeas = daiTuTeaMapper.selectByExample(example);
            daiTuTeaMapper.deleteByExample(example);
            DaiTuTea daiTuTea = daiTuTeas.get(0);

            example = new Example(TeacherStudent.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("teaId",daiTuTea.getId());
            teacherAndStudentMapper.deleteByExample(example);
        }

    }

    @Override
    public List<DaiTuTea> getStatus(Integer userId) {

        Example example = new Example(DaiTuTea.class);
        Example.Criteria exampleCriteria = example.createCriteria();
        exampleCriteria.andEqualTo("userId",userId);
        List<DaiTuTea> daiTuTeas = daiTuTeaMapper.selectByExample(example);

       // Boolean flag = CollectionUtils.isEmpty(daiTuTeas)?false:true;

        return daiTuTeas;
    }

    @Override
    public String selectAllUserId(List<Integer> userIds) {
        StringBuilder msgIds = new StringBuilder();
        for (Integer userId : userIds) {
            User userInfo = userMapper.selectByPrimaryKey(userId);
                //该步即不会第一位有逗号，也防止最后一位拼接逗号！
                if (msgIds.length() > 0) {
                    msgIds.append(",");
                }
                msgIds.append(userInfo.getUserId());
        }

        return msgIds.toString();
    }

}
